import SearchTop from "../../components/newSearchTop.vue";
import SearchTitle from "../../components/newSearchTitle.vue";
import slider from "../../components/sliders.vue";
import getGame from '@/api/getSearch'
import getAwardDetail from '@/api/award/award-add'
import { jsCallNative } from "../../common/callnative"
import axios from 'axios';
import reportEvent from "../../components/report.js"
import $store from "../../components/vuex.js" // 引入新建的store 变量
import bindPhone from "../../components/bindPhone.vue"
import Footer from "../../components/footer.vue"
export default {
    components: {
        SearchTop: SearchTop,
        SearchTitle: SearchTitle,
        slider: slider,
        bindPhone: bindPhone,
        Footer: Footer,
    },
    data() {
        return {
            sliderList: [1],
            // 推荐游戏的图片
            goodGame: [],
            goodGameRank: [],
            listGame: [],
            hotGame: [],
            // 轮播图的图片
            banners: [{ poster: "https://app.caizhanbao.cn/detault/6.png" }, { poster: "https://app.caizhanbao.cn/detault/6.png" }, { poster: "https://app.caizhanbao.cn/detault/6.png" }, { poster: "https://app.caizhanbao.cn/detault/6.png" }],
            userId: '', // lenovoId
            //YY签名以及时间戳
            signs: '',
            timestamp: '',
            playLatests: [],
            gameCategory1: [],
            gameCategory2: [],
            category1: '',
            category2: '',
            softid: "",
            subCategoryIndex: 0,
            categoryIndex: 0,
            token: "",
            channelInfo: {}, // 频道ID
            //进入游戏接口
            gameurl: "http://pitf.vgs.lenovo.com.cn",
            userName: "",
            iconGame: false,
            lenovoUrl: this.gmConf.domainHttps + "privilege.lenovo.com.cn/v3",
            user: {},
            allData: [], // 储存所有数据
            noSerData: false,
            startTime: +new Date(),
            error: "",
            titleImg: "",
            youName: "",
            error1: "",
            bindPhoneBtn: true,
            newService: {},
            myGift: [],
        }
    },
    created() {
        //防止页面后退      
        //处理键盘事件 禁止后退键（Backspace）密码或单行、多行文本框除外 
        function banBackSpace(e) {
            var ev = e || window.event; //获取event对象 
            var obj = ev.target || ev.srcElement; //获取事件源 

            var t = obj.type || obj.getAttribute('type'); //获取事件源类型 

            //获取作为判断条件的事件类型 
            var vReadOnly = obj.getAttribute('readonly');
            var vEnabled = obj.getAttribute('enabled');
            //处理null值情况 
            vReadOnly = (vReadOnly == null) ? false : vReadOnly;
            vEnabled = (vEnabled == null) ? true : vEnabled;

            //当敲Backspace键时，事件源类型为密码或单行、多行文本的， 
            //并且readonly属性为true或enabled属性为false的，则退格键失效 
            var flag1 = (ev.keyCode == 8 && (t == "password" || t == "text" || t == "textarea") &&
                (vReadOnly == true || vEnabled != true)) ? true : false;

            //当敲Backspace键时，事件源类型非密码或单行、多行文本的，则退格键失效 
            var flag2 = (ev.keyCode == 8 && t != "password" && t != "text" && t != "textarea") ?
                true : false;

            //判断 
            if (flag2) {
                return false;
            }
            if (flag1) {
                return false;
            }
        }
        //禁止后退键 作用于Firefox、Opera 
        document.onkeypress = banBackSpace;
        //禁止后退键 作用于IE、Chrome 
        document.onkeydown = banBackSpace;
    },

    computed: { // 计算属性
        /*
            isLogin: false,
            isLoginTwo:true,
            isLoginThree:false,
        */
        isLogin: {
            get() {
                return $store.state.isLogin;
            },
            set() {

            }

        },
        isLoginTwo: {
            get() {
                return $store.state.isLoginTwo;
            },
            set() {

            }

        },
        isLoginThree: {
            get() {
                return $store.state.isLoginThree;
            },
            set() {

            }
        }
    },

    mounted() {
        this.getToken()
        this.getGameLists()
        this.getGameTitle()
        this.sliderInit()
        if (typeof this.$route.query.errorMessage != "undefined" && this.$route.query.errorMessage != "") {
            this.$toast.center("错误")
        };
        reportEvent.pageIn(this.userId, "101")
    },
    beforeDestroy() {
        reportEvent.pageOut(this.userId, this.startTime, "101")
    },

    methods: {
        getUrlParam(par) { // 获取当前url的token
            //获取当前URL
            var local_url = document.location.href;
            //获取要取得的get参数位置
            var get = local_url.indexOf(par + "=");
            if (get == -1) {
                return false;
            }
            //截取字符串
            var get_par = local_url.slice(par.length + get + 1);
            //判断截取后的字符串是否还有其他get参数
            var nextPar = get_par.indexOf("&");
            if (nextPar != -1) {
                get_par = get_par.slice(0, nextPar);
            }
            return get_par;
        },


        //立即注册
        register() {
            var redirect_url = window.location.href;
            redirect_url = encodeURIComponent(redirect_url);
            window.location.href = 'https://lepay.vgs.lenovo.com.cn/#/register?redirect_url=' + redirect_url;
        },

        getToken() { // 获取游客token 如果 URL 里面有token，就从url里面截取，如果没有，说明是游客账号，从接口获取token 
            var token = this.getUrlParam("token")
            var bind = window.sessionStorage.getItem("bind")
            var that = this;

            /*
                游客初次进入 请求游客的lenovoId和token
                通过登录进入 获取url里面的token 然后查获取当前的lenovoId和nickname
                通过绑定手机号的方式  绑定成功后 用返回的lenovoId和token 覆盖原来的lenovoId和token 
                然后刷新页面，然后 永久储存 新的 token  重新进入页面的时候  用这个token 请求喵喵的接口，然后获取新的lenovoId和nickname
            */
            if (token) { // token 存在 url里有token 说明是通过登录进入的 然后去任何地方都要 带token 不然你切换页面就会出现还是游客模式的情况 所以这里要储存一下标识，如果是登录进入的，返回首页需要带回token 
                console.log("token")
                this.token = token
                window.sessionStorage.setItem("login", true); // 储存一个true，然后来标识是登录成功过来的

                this.getUserInfo(token)


            } else if (window.localStorage.getItem("bindToken")) { // 绑定手机号过程完成,储存绑定手机号后返回的接口,



                $store.commit("allShowThree")
                $store.commit("bindPhone", false)
                token = window.localStorage.getItem("bindToken");
                let url = "/token/user/getTourInfo?token=" + token
                this.youGetInfoTwo(url)

            } else { // token 不存在 就获取游客token 

                let url = "/token/user/getTourInfo"
                this.youGetInfo(url)
                this.bindPhoneBtn = true;

            }
        },
        youGetInfo(url) { // 通过请求游客模式接口来获取用户信息 校验是否绑定手机号

            let that = this;

            axios.get(url).then(function(res) {
                that.token = res.data.data.token;
                that.user.nickname = res.data.data.lenovoId;
                that.userId = res.data.data.lenovoId;
                that.titleImg = res.data.imgUrl;

                // 更新vuex 状态
                $store.commit("setToken", that.token)
                $store.commit("setLenovoId", that.userId)
                $store.commit("setUserName", that.user.nickname)

                that.chackPhone(that.userId)
                that.playGameList(that.userId)
            })
        },
        youGetInfoTwo(url) { //通过请求游客模式接口来获取用户信息 不校验是否绑定手机号
            let that = this;

            axios.get(url).then(function(res) {
                that.token = res.data.data.token;
                that.user.nickname = res.data.data.lenovoId;
                that.userId = res.data.data.lenovoId;
                that.titleImg = res.data.imgUrl;

                // 更新vuex 状态
                $store.commit("setToken", that.token)
                $store.commit("setLenovoId", that.userId)
                $store.commit("setUserName", that.user.nickname)

                that.playGameList(that.userId)
            })

        },

        chackPhone(id) { // 校验是否绑定手机号
            let that = this;
            let url = "/back/bss/lid/lidIsBind?lenovoId=" + id;
            axios.get(url).then(function(res) { // 

                if (res.data.code == 0) { // 已经绑定过手机号,该Id就是真实的lenovoId

                    $store.commit("allShowThree")
                    $store.commit("bindPhone", false)

                } else if (res.data.code == 228) { // 未绑定手机号 无效的联想账号

                    $store.commit("allShowTwo");


                    $store.commit("bindPhone", true)
                } else {

                }
            })

        },

        // 我最近在玩的游戏的hover事件
        myHide(index, ev) {
            $(".myGameList .dataList .dataItem").eq(index).children('.itemNum').show()
            $(".myGameList .dataList .dataItem").eq(index).children('.itemStart').hide()
        },
        myShow(index, ev) {
            $(".myGameList .dataList .dataItem").eq(index).children('.itemNum').hide()
            $(".myGameList .dataList .dataItem").eq(index).children('.itemStart').show()
        },


        //获取用户登录信息
        getUserInfo(token) { // 通过token来获取用户的基本信息
            if (token) {
                var ts = this;
                let url = "/token/user/getUserInfo?time=" + new Date().getTime() // 防止ie请求接口缓存
                this.jqajax(url, { type: "GET", dataType: "jsonp", data: { token: ts.token } }, function(res) {
                    ts.user = res.data
                    ts.userName = res.data.nickname
                    // 改变视图状态
                    $store.commit("allShowThree");
                    $store.commit("bindPhone", false)
                    // 更新本地缓存状态
                    $store.commit("setToken", token)
                    $store.commit("setLenovoId", res.data.lenovoId)
                    $store.commit("setUserName", res.data.nickname)

                    ts.userId = res.data.lenovoId

                    ts.playGameList(ts.userId)

                    reportEvent.pageIn(ts.userId, "101")
                })
            } else {

                $store.commit("allShowTwo");
            }
        },

        mustLogin: function() { // 点击开始登陆
            var redirect_url = window.location.href;
            redirect_url = encodeURIComponent(redirect_url);
            window.location.href = 'https://lepay.vgs.lenovo.com.cn/#/login?redirect_url=' + redirect_url;
            reportEvent.pageLoginIn(this.userId)
        },
        loginOut: function() {

            $store.commit("layerShow")

            window.sessionStorage.setItem("token", false);
        },

        showStartGame: function(index, ev) { // 服务器轮播图显示进入游戏
            $(".active .allDataSub li .three")[index].style.display = "none"
            $(".active .allDataSub li .startGame")[index].style.display = "block"
        },
        hideStartGame: function() {
            $(".active .allDataSub li .three").show()
            $(".active .allDataSub li .startGame").hide()
        },
        sliderInit: function() { // 轮播图初始化
            $('.twoCarousel').carousel({
                interval: 5000,
            })
        },

        getGameLists() { // 得到banner和服务器列表轮播图的数据
            // 接口地址在serviceUrl里
            getAwardDetail.getAwardDetail(104).then((res) => {
                $(window).scrollTop(0);
                console.log(res.data)
                // 轮播图
                this.banners = res.data.channels[0].modules[1].elements;
                this.banners.page = res.data.channels[0].channelName;
                this.banners.pageId = res.data.channels[0].id;
                // 精品游戏
                this.goodGame = res.data.channels[0].modules[2].elements.slice(0, 4)
                this.goodGame = this.handleData(this.goodGame)
                console.log(this.goodGame)

                // 热门游戏
                this.hotGame = res.data.channels[0].modules[4].elements.slice(0, 3);
                //  页游精品游戏开服表
                this.goodGameRank = res.data.channels[0].modules[3].elements;
                console.log(this.goodGameRank)

                //处理goodGameRankList

                if (this.banners.length <= 1) {
                    $(".banner-carousel").hide()
                }

                if (JSON.stringify(this.goodGameRank) === "[]") {
                    this.noSerData = true
                } else {
                    this.noSerData = false
                    var goodGameRankList = Math.ceil(this.goodGameRank.length / 10)

                    if (goodGameRankList <= 1) {
                        $(".serviceData").hide()
                    }
                    this.sliderList = [];
                    for (var i = 0; i < goodGameRankList; i++) {

                        (this.sliderList).push(this.goodGameRank.slice(i * 10, (i + 1) * 10))
                    }
                    console.log(this.sliderList)
                }

            })
        },
        // 获取游戏列表
        async getGameTitle() {
            getGame.getMore().then((res) => {
                console.log(res)
                this.gameCategory1 = res.data.first
                this.gameCategory2 = res.data.second.slice(0, 5);
                
                let arr =[];
                this.gameCategory2.map(function(item,index){
                    if(item.cateName != "回合制" && item.cateName != "竞技"){
                        arr.push(item)
                    }
                })
                this.gameCategory2 = arr;
                this.category1 = this.gameCategory1[2].category1
                this.category2 = this.gameCategory2[0].category1
                this.getGame();
            });
        },

        // 点击游戏列表分类
        selectIndex(index, item, ev) {
            let value = ev.target.text
            console.log(value)
            $(".allGameTitle a").removeClass("active")
            $(event.target).addClass("active")
            let arr = []

            if (value == "全部") {
                arr = this.allData
            } else {
                for (var i in this.allData) {
                    if (this.allData[i].category2 == value) {
                        arr.push(this.allData[i])
                    }
                }
            }
            if (JSON.stringify(arr) === '[]') {
                this.iconGame = true
            } else {
                this.iconGame = false
                this.listGame = arr.slice(0, 12);



                this.listGame = this.handleData(this.listGame);

            }

            reportEvent.pageSelect(this.userId)
        },
        handleData(data) {
            // 遍历把235*132的图片加到游戏list里
            console.log(data)
            for (let j = 0; j < data.length; j++) {
                if (!data[j].captureFiles) {
                    data[j].bgUrl = ''
                } else {
                    for (let i = 0; i < data[j].captureFiles.length; i++) {
                        if (data[j].captureFiles[i].size == '270*210') {
                            data[j].bgUrl = data[j].captureFiles[i].url
                        }
                        if (data[j].captureFiles[i].size == '270*600') {
                            data[j].serviceImg = data[j].captureFiles[i].url

                        }

                    }
                    console.log()
                }
            }
            return data
        },
        async getGame() {
            let that = this
            let url = '/search/searchGame?relativeId=48&category1=0&category2=0&page=1';
            axios.get(url).then(function(res) {
                if (JSON.stringify(res.data.datas) === '[]') {
                    that.iconGame = true
                    console.log(that.iconGame)
                } else {
                    that.iconGame = false
                    that.allData = res.data.datas
                    that.listGame = res.data.datas.slice(0, 12)
                    that.listGame = that.handleData(that.listGame)
                }
            })
        },
        goDetails(Id) { // 选择服务器
            console.log(Id)
            if (!this.token) { // 验证token
                window.external.LoginLenovoID(); //登录
                return false;
            }
            let that = this

            this.$router.push({ path: "../newService", query: { gameId: Id } })
        },


        myStartGame: function(game, server) { // 我之前玩过的游戏快速进入游戏

            let url = "https://passport.4366.com/channel/lenovo/gamecenter/login.do?token=" + this.token + "&game=" + game + "&server=" + server + "&ref=LXDT/ZHLX&failUrl=" + encodeURIComponent(window.location.href);
            //let url =this.gameurl+"/gameRedirect/loginGame?"
            //https://pitf.vgs.lenovo.com.cn/gameRedirect/loginGame?cp=YY_GAME&game=DMZT&gameName=传奇世界&serviceName=s16&serviceId=s16
            this.saveGame(window.sessionStorage.getItem("lenovoId"), game, 48, server)
            window.open(url)
            reportEvent.pageStartGame(this.userId)
        },

        playGameList(lenovoId) { // 最近在玩的游戏
            let url = `/gift/api/webpagegame/queryCollectionGames.do?lenovoId=${lenovoId}`
            let that = this;
            axios.get(url).then(function(res) {
                console.log(res)
                if (res.data.code == 0 || JSON.stringify(res.data.gameList) != '[]') {
                    that.playLatests = res.data.gameList.slice(0, 3);
                    $store.commit("playLatests", that.playLatests)

                } else {
                    $toast.center("请求错误")
                }

            }, function(err) {


            })

        },

        //开始游戏
        gameStart(cpId, gameName, softId, serverId, serviceName) { //  cpId 游戏名称  softId   gameId  区服id，区服名
            console.log()
            let that = this;
            var url = `${this.gameurl}/gameRedirect/loginGame?cp=${cpId}_GAME&game=${softId}&gameName=${gameName}&token=${this.token}`


            this.saveGame(window.sessionStorage.getItem("lenovoId"), cpId, softId, 48, serverId, serviceName, gameName)
            window.open(url)
            reportEvent.pageStartGame(this.userId)
        },
        saveGame(lenovoId, cpId, softId, relativeId, serverId, serviceName, gameName) { // 记录玩过的游戏 联想ID cpId softId  平台编号 区服id 区服名 游戏名
            let that = this;
            if (serverId && serviceName) {
                this.resSaveGame(lenovoId, cpId, softId, relativeId, serverId, serviceName, gameName)
            } else {
                console.log(softId)
                let _url = this.gmConf.domainHttps + "unionlogin.4366.com/lenovo/gamecenter/gslist.do?jsonp&serverType=GENERAL&order=opentime:dasc&gsPageSize=5&online" + "&game=" + softId + "&gsPageNo=1"
                console.log(_url)
                that.jqajax(_url, { type: "post", dataType: "jsonp" }, function(res) {

                    var _servers = res[softId].servers;
                    var arr = []
                    for (var item in _servers) {
                        arr.push(_servers[item]);
                    }
                    that.newService = arr[0]
                    console.log(that.newService)

                    that.resSaveGame(lenovoId, cpId, softId, relativeId, that.newService.id, that.newService.name, gameName)

                });
            }

        },
        resSaveGame(lenovoId, cpId, softId, relativeId, serverId, serviceName, gameName) {
            let that = this
            let url = `/gift/api/webpagegame/collectionGame.do?lenovoId=${lenovoId}&relativeId=${relativeId}&serverId=${serverId}&softId=${softId}&serverName=${serviceName}&gameName=${gameName}&softName=${cpId}`;
            axios.get(url).then(function(res) {
                if (res.data.code == 0) {

                } else {
                    that.$toast.center("请求错误")
                }

            }, function(err) {

            })

        },
        //客户端弹窗
        popVideo(_url) {
            var ts = this;
            if (!_url || !ts.isLenovo()) return;
            if (!ts.isIe()) {
                callHostFunction.callBackVideo(_url, ts.softBrowser);
            } else {
                window.external.callBackVideo(_url, ts.softBrowser);
            }
        },

        openWin(url) {
            $('body').append($('<a href="' + url + '" target="_blank" id="openWin"></a>'))
            document.getElementById("openWin").click(); //点击事件  
            $('#openWin').remove();
        },
        moreGame() {
            let that = this
            if (!this.token) { // 验证token
                window.external.LoginLenovoID(); //登录
                return false;
            }

            this.$router.push({ path: "../newAllGame" })

            window.sessionStorage.setItem("index", "1");
            reportEvent.pageMoreGame(this.userId)
        },
        getGift() { // 领取礼包

            this.$router.push({ path: "../newGiftCenter/", query: {} })
        },
        pCenter() {
            this.$router.push({ path: "../newPcenter" })
            window.sessionStorage.setItem("index", "2");

        },


    }

}